package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Fdjthsensor;
import com.example.onlinemonitoring.model.Fdjthhistory;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Dqjdcwsensor;
import com.example.onlinemonitoring.serviceImpl.FdjthsensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*这里beanName需要和数据库Appdevice中的simple对应并加上Com,不对应请自行修改
    例:simple:dlhl
    @Service("dlhlCom")
*/
@Service("fdjthCom")
@Scope("prototype")
public class FdjthCom extends CommPortManager {
        @Autowired
        private FdjthsensorServiceImpl fdjthsensorServiceImpl;

        @Override
        public void receiveData(String str) {
            try {
                str = str.toUpperCase();
                setText(str);
                //条件判断自己写
                String addrstr = str.substring(0, 2);
                Integer addr = parseHex4(addrstr);
    
                if (!"03".equals(str.substring(2, 4)))
                return;

                reSend[addrindex] = 0;
                addrindex++;
                if (str.length()<12)
                return;
                int startindex=6;
                Fdjthsensor fdjthsensor =  new Fdjthsensor();
                fdjthsensor.setStationid(ad.getStationid());
                fdjthsensor.setDevicegroup(ad.getDevicegroup());
                fdjthsensor.setDeviceaddr(addr);
                fdjthsensor = fdjthsensorServiceImpl.getModel(fdjthsensor);
                if (fdjthsensor == null) {
                    setText("当前数据库无监测点：设备地址" + addr + "的监测点" +1 + " ！ 请先添加该监测点！");
                    return;
                }


                if(fdjthsensor.getInuse()==0)
                    return;
                startindex=6;
                fdjthsensor.setLasthumidityvalue1    (parseHex88(str.substring(startindex , startindex +=4))/10);  
                fdjthsensor.setLasttemperaturevalue1 (parseHex88(str.substring(startindex , startindex +=4))/10);

                setText("温度：" + fdjthsensor.getLasttemperaturevalue1()+ "℃ " + "湿度：" + fdjthsensor.getLasthumidityvalue1() + "% " );

                AddAndUpdate(fdjthsensor);
            
            } catch (Exception ex) {
                ex.printStackTrace();
                setText("从设备返回的数据有误！请检查串口！");
            }
        }

        @Transactional
        private void AddAndUpdate(Fdjthsensor record) {
            int alarmLevel = 0;// 报警等级
            String alarmMessage = "";// 报警消息
            //报警逻辑
            //这里写报警逻辑
            if (
                record.getTemperaturealarmvalue() == null ||
                record.getTemperaturealarmrelievevalue() == null ||
                record.getTemperaturewarnvalue() == null ||
                record.getTemperaturewarnrelievevalue() == null ||
                record.getHumidityalarmvalue() == null ||
                record.getHumidityalarmrelievevalue() == null ||
                record.getHumiditywarnvalue() == null ||
                record.getHumiditywarnrelievevalue() == null 
            ) {
                setText("设备地址" + record.getDeviceaddr() + " 未设置报警值！");
                return;
            }
            List<Integer> array = new ArrayList<>();
            String alm = "";
            int temperaturealm=0,humidityalm=0;
            record.setLasttemperaturealarm(
                GetAlarmStatus(isnull(record.getLasttemperaturevalue1()), isnull(record.getTemperaturealarmvalue()),
                        isnull(record.getTemperaturealarmrelievevalue()), isnull(record.getTemperaturewarnvalue()),
                        isnull(record.getTemperaturewarnrelievevalue()),
                        isnull(record.getLasttemperaturealarm()), true, "温度", record.getDevicegroup(),record.getDeviceaddr(),
                        record.getPointname()));
            alarmMessage += GetAlarmMessage(record.getLasttemperaturealarm(), "温度");      
            array.add(record.getLasttemperaturealarm());
            record.setLasthumidityalarm(
                GetAlarmStatus(isnull(record.getLasthumidityvalue1()), isnull(record.getHumidityalarmvalue()),
                        isnull(record.getHumidityalarmrelievevalue()), isnull(record.getHumiditywarnvalue()),
                        isnull(record.getHumiditywarnrelievevalue()),
                        isnull(record.getLasthumidityalarm()), true, "湿度", record.getDevicegroup(),record.getDeviceaddr(),
                        record.getPointname()));
            alarmMessage += GetAlarmMessage(record.getLasthumidityalarm(), "湿度");      
            array.add(record.getLasthumidityalarm());
            alarmLevel = HexUtil.MAX(array);
            record.setLastalarmlevel(alarmLevel);
            record.setLastalarmmessage(alarmMessage);
            record.setLastcommunicationstatus(0);
            record.setLastdatatime(new Date());
            record.setLasthisdatatime(addHistory(fdjthsensorServiceImpl.getModel(record)));
            if ( fdjthsensorServiceImpl.Update(record, false) == 0) {
                setText("更新实时数据失败，请检查数据库连接");
            }
        }
        private Date addHistory(Fdjthsensor sensor) {
            if (sensor != null) {
                if (sensor.getLasthisdatatime() == null) {
                    add(sensor);
                    return new Date();
                } else {
                    long lasttime = 0;
                    long nowtime = 0;
                    try {
                        lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                        nowtime = HexUtil.todate(new Date()).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    int timersp = 60000;
                    if (sensor.getLastalarmlevel() != 0) {
                        timersp = ad.getHisalarmtimersp()*1000;
                    } else {
                        timersp = ad.getHistimersp()*1000;
                    }
                    if (lasttime + timersp < nowtime) {
                        add(sensor);
                        return new Date();
                    }
                }
            }
            return null;
        }

        private void add(Fdjthsensor sensor) {
            Fdjthhistory his = new Fdjthhistory();
            his.setDeviceaddr(sensor.getDeviceaddr());
            his.setDevicegroup(sensor.getDevicegroup());
            his.setAlarmlevel(sensor.getLastalarmlevel());
            his.setAlarmmessage(sensor.getLastalarmmessage());
            his.setDatatime(sensor.getLastdatatime());
            his.setPointname(sensor.getPointname());
            his.setStationid(sensor.getStationid());
            //需要添加自己定义的属性
            his.setTemperaturevalue1(sensor.getLasttemperaturevalue1());
            his.setHumidityvalue1(sensor.getLasthumidityvalue1());
            fdjthsensorServiceImpl.Add(his);
        }

        public static float parseHex88(String num) {
            int ret = Integer.parseInt(num, 16);
            if (num.length() == 2) {
                return ret;
            } else if (num.length() == 4) {
                ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
                return ret;
            } else {
                throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
            }
        }
        @Async("threadPool")
        public void startSendThread(Appdevice Appdevice) throws Exception {
            checkType = "crc16";
            issend.put(Thread.currentThread().getId(), true);
            String cstr = "";
            String cmdtype = "";
            String nametype = "";
            int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
            while (issend.get(Thread.currentThread().getId()) != null) {
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                    addrindex = Appdevice.getAddrmin();
                cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                cstr = cstr + CRC16.calcCrc16(cstr);
                try {
                    Send(cstr);
                } catch (Exception EX) {
                     setText(EX.toString());
                }
               // setText("向" + Appdevice.getName() + "设备发送指令" + cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > 3) {
                fdjthsensorServiceImpl.UpdateStatus(ad, addrindex,1);
                reSend[addrindex] = 0;
                addrindex++;
                }
                Thread.sleep(timersp);
            }
        }

        // @Async("threadPool")
        // public void startReceiveThread(){
        //     isrecv.put(Thread.currentThread().getId(), true);
        //     while (isrecv.get(Thread.currentThread().getId()) != null) {
        //         //这里根据实际协议替换,解析方法recvCrc16;recvSum();
        //         recv();
        //         try {
        //             Thread.sleep(interval);
        //         } catch (InterruptedException e) {
        //             e.printStackTrace();
        //         }
        //     }
        // }
}
